"use client";

import { useEffect, useState, useRef } from 'react';
import { useConversation } from '@/context/conversationContext';
import { useAuth } from '@/context/authContext';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Loader2, Send, Info, Plus } from 'lucide-react';
import { toast } from 'sonner';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogClose, DialogFooter } from '@/components/ui/dialog';
import { del, get, post, put } from '@/lib/request';

export default function ChatWindow() {
  const { 
    currentConversation, 
    messages,
    addMessage,
    fetchMoreMessages,
    hasMoreMessages,
    isMessagesLoading 
  } = useConversation();
  const { user } = useAuth();
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const messageContainerRef = useRef<HTMLDivElement>(null);
  const [groupInfoOpen, setGroupInfoOpen] = useState(false);
  const [groupInfo, setGroupInfo] = useState<{name:string,avatar:string|null,ownerId:string}|null>(null);
  const [members, setMembers] = useState<{id:string,username:string,avatar:string|null}[]>([]);
  const [groupLoading, setGroupLoading] = useState(false);
  const [inviteOpen, setInviteOpen] = useState(false);
  const [allFriends, setAllFriends] = useState<{id:string,username:string,avatar:string|null}[]>([]);
  const [inviteSelected, setInviteSelected] = useState<string[]>([]);
  const [inviting, setInviting] = useState(false);
  const [editingName, setEditingName] = useState(false);
  const [newGroupName, setNewGroupName] = useState('');
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [avatarUploading, setAvatarUploading] = useState(false);

  useEffect(() => {
    // 滚动到底部
    if (messageContainerRef.current) {
      // 在初次加载和新消息时滚动到底部
      const shouldScroll = messageContainerRef.current.scrollTop + messageContainerRef.current.clientHeight >= messageContainerRef.current.scrollHeight - 30;
      if (shouldScroll) {
         messageContainerRef.current.scrollTop = messageContainerRef.current.scrollHeight;
      }
    }
  }, [messages]);

  useEffect(() => {
    if (groupInfoOpen && currentConversation?.type === 'group') {
      fetchGroupDetails();
    }
  }, [groupInfoOpen, currentConversation]);

  const handleScroll = () => {
    if (messageContainerRef.current) {
      const { scrollTop } = messageContainerRef.current;
      if (scrollTop === 0 && hasMoreMessages && !isMessagesLoading) {
        fetchMoreMessages();
      }
    }
  };

  const handleSend = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!input.trim() || !currentConversation) return;
    setSending(true);

    try {
      const body = {
        content: input.trim(),
        conversationId: currentConversation.id,
      };
      const res = await post('messages', body);
      if (!res.data) throw new Error('发送失败');
      addMessage(res.data);
      setInput('');
    } catch (e: any) {
      toast.error(e.message);
    } finally {
      setSending(false);
    }
  }

  const fetchGroupDetails = async () => {
    setGroupLoading(true);
    try {
      const res = await get(`conversations/${currentConversation!.id}/details`);
      const data = res.data;
      if (!data) throw new Error('获取群聊信息失败');
      setGroupInfo({ name: data.name, avatar: data.avatar, ownerId: data.ownerId });
      setMembers(data.members);
    } catch {
      setGroupInfo(null);
      setMembers([]);
      toast.error('获取群聊信息失败');
    } finally {
      setGroupLoading(false);
    }
  }

  const fetchAllFriends = async () => {
    try {
      const res = await get('friends/list');
      const data = res.data;
      if (data === null) {
        throw new Error('获取好友失败');
      }
      setAllFriends(data);
    } catch (error) {
      setAllFriends([]);
    }
  }

  const handleInvite = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!inviteSelected.length) return;
    setInviting(true);
    try {
      const res = await post(`groups/${currentConversation!.id}/members`, { members: inviteSelected });
      if (!res.data) throw new Error('邀请失败');
      toast.success('邀请成功');
      setInviteOpen(false);
      // 清空ids
      setInviteSelected([]);
      // 获取members
      fetchGroupDetails();
    } catch (e: any) {
      toast.error(e.message);
    } finally {
      setInviting(false);
    }
  }

  const handleRemoveMember = async (memberId: string) => {
    if (!window.confirm('确定要移除该成员？')) return;
    try {
      const res = await del(`groups/${currentConversation!.id}/members/${memberId}`);
      if (!res.data) throw new Error('移除失败');
      toast.success('已移除该成员');
      fetchGroupDetails();
    } catch (e: any) {
      toast.error(e.message);
    }
  }

  const handleExitGroup = async () => {
    if (!window.confirm('确定要退出群聊吗？')) return;
    try {
      const res = await del(`groups/${currentConversation!.id}/members/me`);
      if (!res.data) throw new Error('退出失败');
      toast.success('已退出群聊');
      setGroupInfoOpen(false);
      // TODO: 自动刷新会话列表
    } catch (e: any) {
      toast.error(e.message);
    }
  }

  const handleDeleteGroup = async () => {
    if (!window.confirm('确定要解散群聊吗？')) return;
    try {
      const res = await del(`groups/${currentConversation!.id}`);
      if (!res.data) throw new Error('解散失败');
      toast.success('群聊已解散');
      setGroupInfoOpen(false);
      // TODO: 自动刷新会话列表
    } catch (e: any) {
      toast.error(e.message);
    }
  }

  const handleUpdateName = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newGroupName.trim() || !currentConversation) return;
    try {
      const data = {
        name: newGroupName.trim(),
      }
      const res = await put(`groups/${currentConversation.id}`, data);
      if (!res.data) throw new Error('修改群名失败');
      toast.success('群名已更新');
      setEditingName(false);
      fetchGroupDetails();
    } catch (e: any) {
      toast.error(e.message);
    }
  }

  const handleAvatarChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e.target.files || !e.target.files[0]) return;
    setAvatarUploading(true);
    const formData = new FormData();
    formData.append('avatar', e.target.files[0]);
    try {
      const res = await post(`groups/${currentConversation!.id}/avatar`, formData);
      if (!res.data) throw new Error('上传失败');
      toast.success('头像已更新');
      fetchGroupDetails();
    } catch (e: any) {
      toast.error(e.message);
    } finally {
      setAvatarUploading(false);
    }
  }

  if (!currentConversation) return null;

  return (
    <section className="flex-grow flex flex-col">
      <header className="p-4 border-b flex items-center justify-between">
        <h2 className="text-lg font-semibold">{currentConversation.name}</h2>
        {currentConversation.type === 'group' && (
          <Button variant="ghost" className="ml-2 p-2" title="群聊" onClick={() => setGroupInfoOpen(true)}>
            <Info size={20} />
          </Button>
        )}
      </header>
      <div 
        className="flex-grow p-4 bg-gray-100 overflow-auto"
        ref={messageContainerRef}
        onScroll={handleScroll}
      >
        {isMessagesLoading && messages.length === 0 ? (
          <div className="flex justify-center items-center h-full">
            <Loader2 className="animate-spin mr-2" /> 加载中...
          </div>
        ) : (
          <>
            {isMessagesLoading && (
              <div className="flex justify-center py-2">
                <Loader2 className="animate-spin text-gray-400" />
              </div>
            )}
            {messages.map(msg => {
              // 系统消息
              if (msg.type === 'SYSTEM') {
                return (
                  <div key={msg.id} className="text-center text-xs text-gray-500 py-2">
                    {msg.content}
                  </div>
                )
              }
              return (
                <div key={msg.id} className={`flex items-start my-4 ${msg.sender.id === user!.id ? 'flex-row-reverse' : ''}`}>
                  <Avatar className="h-8 w-8">
                    <AvatarImage src={msg.sender.avatar || undefined} alt={msg.sender.username} />
                    <AvatarFallback>{msg.sender.username?.charAt(0).toUpperCase()}</AvatarFallback>
                  </Avatar>
                  <div className={`mx-3 p-3 rounded-lg max-w-lg text-sm ${
                    msg.sender.id === user!.id 
                      ? 'bg-blue-500 text-white' 
                      : 'bg-white dark:bg-stone-700'
                  }`}>
                    {msg.content}
                  </div>
                </div>
              )
            })}
          </>
        )}
      </div>
      <form onSubmit={handleSend}>
        <footer className="p-4 border-t bg-white flex items-center">
          <Input
            placeholder="输入消息..."
            className="flex-1 mr-2"
            value={input}
            onChange={e => setInput(e.target.value)}
            disabled={sending || !currentConversation}
          />
          <Button type="submit" disabled={sending || !input.trim()}>
            {sending ? <Loader2 className="animate-spin" size={18}/> : <Send size={18} />}
          </Button>
        </footer>
      </form>
      <Dialog open={groupInfoOpen} onOpenChange={setGroupInfoOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>群聊</DialogTitle>
          </DialogHeader>
          {groupLoading ? (
            <div className="flex items-center justify-center py-8 text-gray-400">
              <Loader2 className="animate-spin mr-2" /> 加载中...
            </div>
          ) : groupInfo ? (
            <>
              <div className="flex items-center mb-4">
                <div className="relative group">
                  <Avatar className="h-12 w-12 cursor-pointer" onClick={() => {
                    if (user!.id === groupInfo.ownerId) fileInputRef.current?.click();
                  }}>
                    <AvatarImage src={groupInfo.avatar || undefined} alt={groupInfo.name} />
                    <AvatarFallback>{groupInfo.name?.charAt(0).toUpperCase()}</AvatarFallback>
                  </Avatar>
                  {user!.id === groupInfo.ownerId && (
                    <>
                      <input
                        type="file"
                        accept="image/*"
                        ref={fileInputRef}
                        className="hidden"
                        onChange={handleAvatarChange}
                        disabled={avatarUploading}
                      />
                      <span className="absolute bottom-0 left-0 right-0 text-center text-xs text-blue-500 bg-white/80 rounded-b opacity-0 group-hover:opacity-100 transition">更換頭像</span>
                    </>
                  )}
                </div>
                <div className="ml-4 flex flex-col">
                  {editingName ? (
                    <form onSubmit={handleUpdateName} className="flex items-center gap-2">
                      <input
                        className="border rounded px-2 py-1 text-sm"
                        value={newGroupName}
                        onChange={e => setNewGroupName(e.target.value)}
                        autoFocus
                        disabled={avatarUploading}
                      />
                      <Button size="sm" type="submit">保存</Button>
                      <Button size="sm" variant="ghost" type="button" onClick={() => setEditingName(false)}>取消</Button>
                    </form>
                  ) : (
                    <div className="flex items-center gap-2">
                      <span className="font-bold text-lg cursor-pointer" onClick={() => {
                        if (user!.id === groupInfo.ownerId) {
                          setEditingName(true);
                          setNewGroupName(groupInfo.name);
                        }
                      }}>{groupInfo.name}</span>
                      {user!.id === groupInfo.ownerId && <span className="text-xs text-blue-500 cursor-pointer" onClick={() => {
                        setEditingName(true);
                        setNewGroupName(groupInfo.name);
                      }}>✎</span>}
                    </div>
                  )}
                  <div className="text-xs text-gray-500">ID: {currentConversation!.id}成员 {members.length} 人</div>
                </div>
              </div>
              <div className="mb-2 font-medium">
                <span>成员列表</span>
              </div>
              <div className="grid grid-cols-5 gap-3">
                {members.map(m => (
                  <div key={m.id} className="flex flex-col items-center text-xs relative group">
                    <Avatar className="h-10 w-10">
                      <AvatarImage src={m.avatar || undefined} alt={m.username} />
                      <AvatarFallback>{m.username?.charAt(0).toUpperCase()}</AvatarFallback>
                    </Avatar>
                    <span className="mt-1 truncate w-full text-center">
                      {m.username}
                      {m.id === groupInfo.ownerId && <span className="ml-1 text-yellow-500" title="群主">👑</span>}
                    </span>
                    {user!.id === groupInfo.ownerId && m.id !== user!.id && (
                      <button className="absolute -top-1 -right-1 p-0.5 text-red-400 hover:text-red-600 bg-white rounded-full shadow-md invisible group-hover:visible leading-none text-lg" title="移除成員" onClick={() => handleRemoveMember(m.id)}>
                        ×
                      </button>
                    )}
                  </div>
                ))}
                {/* Invite Button */}
                <div 
                  className="flex flex-col items-center justify-center text-xs cursor-pointer"
                  onClick={() => { setInviteOpen(true); fetchAllFriends(); }}
                >
                  <div className="h-10 w-10 rounded-full border-2 border-dashed flex items-center justify-center hover:bg-gray-100 dark:hover:bg-stone-700">
                    <Plus size={20} className="text-gray-400" />
                  </div>
                  <span className="mt-1">邀请</span>
                </div>
              </div>
              <div className="mt-6 flex justify-end gap-2">
                {user!.id === groupInfo.ownerId ? (
                  <Button variant="destructive" onClick={handleDeleteGroup}>解散群聊</Button>
                ) : (
                  <Button variant="outline" onClick={handleExitGroup}>退出群聊</Button>
                )}
              </div>
            </>
          ) : (
            <div className="text-center text-red-400 py-8">加载失败</div>
          )}
          <DialogClose asChild>
            <Button className="mt-4 px-4 py-2 rounded bg-gray-100 hover:bg-gray-200">关闭</Button>
          </DialogClose>
        </DialogContent>
      </Dialog>
      <Dialog open={inviteOpen} onOpenChange={setInviteOpen}>
        <DialogContent>
          <form onSubmit={handleInvite}>
            <DialogHeader>
              <DialogTitle>邀请好友入群</DialogTitle>
            </DialogHeader>
            <div className="max-h-40 overflow-auto border rounded p-2 bg-gray-50 mb-3">
              {allFriends.filter(f => !members.some(m => m.id === f.id)).length === 0 ? (
                <div className="text-gray-400 text-sm">暂无可邀请好友</div>
              ) : (
                allFriends.filter(f => !members.some(m => m.id === f.id)).map(f => (
                  <label key={f.id} className="flex items-center mb-1 cursor-pointer">
                    <input
                      type="checkbox"
                      className="mr-2"
                      checked={inviteSelected.includes(f.id)}
                      onChange={e => {
                        if (e.target.checked) setInviteSelected(sel => [...sel, f.id]);
                        else setInviteSelected(sel => sel.filter(id => id !== f.id));
                      }}
                      disabled={inviting}
                    />
                    <Avatar className="h-6 w-6">
                      <AvatarImage src={f.avatar || undefined} alt={f.username} />
                      <AvatarFallback>{f.username?.charAt(0).toUpperCase()}</AvatarFallback>
                    </Avatar>
                    <span className="ml-2">{f.username}</span>
                  </label>
                ))
              )}
            </div>
            <DialogFooter>
              <Button type="submit" disabled={inviting || inviteSelected.length === 0}>
                {inviting ? '邀请中...' : '邀请'}
              </Button>
              <DialogClose asChild>
                <Button type="button" variant="ghost">取消</Button>
              </DialogClose>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </section>
  );
} 